<template>
	<!-- 选择点位天地图 -->
	<view class="map-page-wrapper">
		<view class="map-box">
			<jLeaflet ref="map" :map-key="mapKey" :lonlat="lonlat" :zoom="zoom" :show-center-icon="showCenterIcon" :center-icon="centerIcon" :show-location-icon="showLocationIcon" :on-location="location" :on-loaded="loaded" :on-start-drag="startDrag" :on-zoom-end="zoomEnd" :on-end-drag="endDrag"
				:zoomMapT="zoomMapT" @calolBack="calolBack" />
		</view>
		<view class="tool-box">
			<view class="topBox">
				<!-- <u-icon name="arrow-left" color="#ffffff" size="22" @click="backBtn"></u-icon> -->
				<view>
					<u-button type="primary" @click="choiceAddressBtn" customStyle="{width: 60rpx;height: 60rpx;}" color="#5f8dfe" text="确定"></u-button>
				</view>
			</view>
			<!-- <view class="tool" @tap="look()">查看</view> -->
		</view>
		<u-popup :show="true" :overlay="false" round='10'>
			<view class="upopupAddress">
				<u-search placeholder="搜索地点" inputAlign="center" @search="ssearch" v-model="keyword" :showAction="false"></u-search>
				<view style="height: 45vh;overflow: auto;" v-show="!uLoading">
					<view class="singlePio" v-for="item,index in poiList" :key="index">
						<view class="poiItem" @click="choiceItemBtn(poiList,item)">
							<view class="title">{{item.name}}</view>
							<view class="contents">
								<view class="distance">{{item.roadDistince}}</view>
								<view class="address">{{item.address}}</view>
							</view>
						</view>
						<view class="choice" v-show="item.isChoice">
							<u-icon name="checkmark" color="#7fa3fe" size="22"></u-icon>
						</view>
					</view>
				</view>
				<view v-show="uLoading" style="margin-top: 40rpx;">
					<u-loading-icon></u-loading-icon>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import jLeaflet from '@/components/jLeaflet.vue'
	// 导入本地图标
	import Vector from '@/static/mapImg/Vector.png';
	import point from '@/static/mapImg/point.png';
	import dqwz from '@/static/mapImg/dqwz.png';
	import { getSearchBounds } from '@/utils/SearchRangePoint.js' //地理空间搜索范围计算函数


	
	export default {
		components: {
			jLeaflet
		},
		data() {
			return {
				// 天地图官网地址 https://oauth.tianditu.gov.cn/
				mapKey: "a089dabb9c75cd0944e1013b54611773",
	
				// 中心位置
				lonlat: [111.306610,30.689890], // 故宫
				// lonlat: [],
				// 缩放
				zoom: 16,
				// 地图展示类型
				type: 0,
				// 显示中心图标
				showCenterIcon: true,
				// 显示定位图标
				showLocationIcon: false,
				// 不设置使用默认图标
				centerIcon: "",
				zoomMapT: 0,
				// 用户当前位置
				userLocation: {
					lon: 111.306610,
					lat: 30.689890,
					altitude: 0, // 海拔
					address: '',
				},
				keyword: '', // 搜索关键字
				inputFocus: false, // input输入框焦点状态
				poiList: [], // poi点列表
				// 选中的poi点
				choicePoi: {
					address: '', // 此点的具体信息（分类）
					name: '', // 此点最近地点信息
					roadDistince: '', //此点距离此路的距离		
				},
				uLoading: false, // 拖拽loading
 
			};
		},
		async onLoad() {
			// 获取当前用户位置
			await this.getLocation();
			console.log('先获取位置', this.lonlat);
		},
		mounted() {
			console.log('再绑定组件', this.lonlat);
			// 绑定组件
			this.map = this.$refs.map;
		},
		methods: {
			// 返回
			backBtn() {
				uni.navigateBack();
			},
			// 搜索
			ssearch() {
				this.searchPoi('2')
			},
 
			// 确定按钮
			choiceAddressBtn() {
				uni.$emit('choiceAddressPoi', this.choicePoi)
				//this.backBtn()
			},
			// 获取当前用户位置
			async getLocation() {
				const that = this;
				console.log('进入获取当前用户位置');
				await uni.getNetworkType({
					success: async function(res) {
						console.log('获取网络状态', res.networkType);
						if (res.networkType === 'none') {
							await plus.geolocation.getCurrentPosition(successCB => {
								console.log('系统--获取当前用户位置--无网', successCB);
								that.userLocation.lon = successCB.coords.longitude;
								that.userLocation.lat = successCB.coords.latitude;
								that.userLocation.altitude = successCB.coords.altitude;
								that.lonlat[0] = res.longitude
								that.lonlat[1] = res.latitude
							}, errorCB => {
								console.log('系统--获取当前用户位置失败--无网', errorCB);
							}, {
								provider: 'system',
								coordsType: 'wgs84',
								// coordsType: 'gcj02',
								// enableHighAccuracy: true, //是否高精确度获取位置信息
								// timeout: 10000, //  获取位置信息的超时时间
								// maximumAge: 0, // 获取位置信息的间隔时间
								geocode: true // 是否解析地址信息
							})
						} else {
							await uni.getLocation({
								// geocode: true,
								// type: 'gcj02',
								// altitude: true, 
								// isHighAccuracy: true,
								// highAccuracyExpireTime: 30000,
								success: function(res) {
									console.log('uni-获取当前用户位置--有网', res);
									that.userLocation.lon = res.longitude;
									that.userLocation.lat = res.latitude;
									console.log('222');
									that.userLocation.altitude = res.altitude;
									console.log('333');
									that.lonlat[0] = that.userLocation.lon;
									console.log('444');
									that.lonlat[1] = that.userLocation.lat;
									console.log('5555');
									console.log('that.userLocation用户信息', that.userLocation);
								},
								fail: function(res) {
									console.log('uni-获取当前用户位置失败--有网', res);

									//设置默认经纬度---宜昌111.306610,30.689890

										that.userLocation.lon = 111.306610;
									that.userLocation.lat = 30.689890;

								}
							});
						}
					}
				});
 
			},
			look() {
				console.log('点击查看');
				// console.log('地图页面this.map.look()', this.map.look());
				this.map.look()
			},
			calolBack(val) {
				console.log('calolBack', val);
				// this.zoomMapT = val.zzz
			},
			location() {
				console.log("点击定位按钮回调");
				this.map.resize()
			},
			// 天地图逆地理解析
			getAddress(data) {
				if(data && data.lonlat){
					uni.request({
						url: `http://api.tianditu.gov.cn/geocoder?postStr={ 'lon':${data.lonlat[0]}, 'lat': ${data.lonlat[1]}, 'ver':1 }&type=geocode&tk=${this.mapKey}`, //天地图逆地理解析接口
						success: (res) => {
							console.log('天地图逆地理解析res.data', res.data);
							const obj = {
								address: res.data.result.formatted_address,
								name: res.data.result.addressComponent.address,
								hotPointID: "1", // 热点id
								location: res.data.result.location,
								lonlat: `${res.data.result.location.lon},${res.data.result.location.lat}`, // 经纬度 x,y
								isChoice: true, // 是否选中
								info: res.data.result.addressComponent
							}
							this.poiList = [obj]
							this.choicePoi = obj
							this.searchPoi('1', obj)
						}
					});
				}
			
			},
			// 点击勾选poi点
			choiceItemBtn(list, item) {
				// 选中item的isChoice为true
				item.isChoice = true
				// 其他item的isChoice为false
				list.forEach(item2 => {
					if (item2.hotPointID !== item.hotPointID) {
						item2.isChoice = false
					}
				})
				this.choicePoi = item
				this.poiList = list
				console.log('点击勾选poiList', this.poiList);
				console.log('点击勾选choicePoi', this.choicePoi);
				const lonlat = item.lonlat.split(',')
				this.map.setCenter(lonlat[0], lonlat[1])
			},
			// 天地图搜索附近poi点信息
			searchPoi(type, data) {
				// type 移动地图搜索 1   输入框搜索 2
				let seaechVal = ''
				let option = {}
				if (type === '1') {
					seaechVal = data.address
					option = {
						latitude: +data.location.lat, // 纬度
						longitude: +data.location.lon, // 经度
						distance: 100 // 范围 100公里
					}
				} else {
					option = {
						latitude: +this.lonlat[1], // 纬度
						longitude: +this.lonlat[0], // 经度
						distance: 100 // 范围 100公里
					}
					seaechVal = this.keyword
				}
 
				const pointRange = getSearchBounds(option)
				const entents = pointRange.minLon + ',' + pointRange.minLat + ',' + pointRange.maxLon + ',' + pointRange.minLat
				const start = 1
				const url = `http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${seaechVal}","level":"${this.zoom}","mapBound":"${entents}","queryType":1,"start":4,"count":10}&type=query&tk=${this.mapKey}`
				console.log('url', url);
				uni.request({
					url: url, //天地图搜索附近poi点信息接口
					success: (res) => {
						this.uLoading = false
						console.log('天地图搜索附近poi点信息res.data', res.data);
						if (+res.data.count > 0 && type === '1') {
							this.poiList = [...this.poiList, ...res.data.pois];
						} else {
							this.poiList = res.data.pois;
							// 移动到第一个点
							const lonlat = this.poiList[0].lonlat.split(',')
							this.map.setCenter(lonlat[0], lonlat[1])
						}
						this.poiList.forEach(item => {
							this.$set(item, 'isChoice', false)
							// 计算最新两点之间的距离
							const lonlat = item.lonlat.split(',')
							let distance = this.calculateDistanceBackup(
								this.lonlat[1],
								this.lonlat[0],
								lonlat[1],
								lonlat[0],
							)
							if (distance > 1000) {
								distance = (distance / 1000).toFixed(2) + 'km'
							} else {
								distance = distance + 'm'
							}
							this.$set(item, 'roadDistince', distance)
							// 若distance单位为m且小于100m则显示为100m内
							if (distance.includes('m') && distance.replace('m', '') < 100) {
								this.$set(item, 'roadDistince', '100m内')
							}
						})
						this.poiList[0].isChoice = true
						this.choicePoi = this.poiList[0]
					}
				});
			},
			// 根据定位坐标与传入坐标计算距离
			calculateDistanceBackup(lat1, lng1, lat2, lng2) {
				// const R = 6371000 // 地球半径，单位米 
				const R = 6378137 // 赤道半径，单位米 
				const dLat = this.toRad(lat2 - lat1)
				const dLon = this.toRad(lng2 - lng1)
				const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2)
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
 
				return Math.round(R * c)
			},
			// 将角度转换为弧度
			toRad(degree) {
				return degree * Math.PI / 180
			},
 
			// 地图创建完成
			loaded(data) {
				console.log("地图创建完成", data);
				this.getAddress(data) // 天地图逆地理解析
			},
			// 地图缩放完成
			zoomEnd(lon, lat) {
				console.log("地图缩放完成", lon, lat);
			},
			// 开始拖拽
			startDrag(lon, lat) {
				this.uLoading = true
				console.log("开始地图拖拽", lon, lat);
			},
			// 结束拖拽
			endDrag(lon, lat) {
				const data = {
					lonlat: [lon, lat]
				}
				this.getAddress(data) // 天地图逆地理解析
				console.log("结束地图拖拽", lon, lat);
			},
			setZoom(zoom) {
				this.zoom += zoom;
				if (this.zoom <= 10) this.zoom = 1;
				if (this.zoom >= 20) this.zoom = 20;
				this.map.setZoom(this.zoom);
			},
			setType(type) {
				// type 0矢量地图 1卫星地图 其他矢量地图
				this.type = type;
				this.map.setType(this.type);
			},
			setCenter(lon, lat) {
				this.lonlat = [lon, lat];
				this.map.setCenter(lon, lat);
			},
			setIcon() {
				// 默认图标和icon切换显示
				this.centerIcon = this.centerIcon ? "" : Vector;
			},
		}
	};
</script>
 
<style scoped lang="scss">
	.map-page-wrapper {
		width: 100%;
		height: 100vh;
 
		.map-box {
			width: 100%;
			height: 100%;
		}
 
		.tool-box {
			position: absolute;
			// 天地图默认z-index:400 需要大于400
			z-index: 999;
			top: 80rpx;
			left: 20rpx;
			width: 100%;
			border-radius: 8rpx;
			padding: 16rpx;
			// display: flex;
			// flex-wrap: wrap;
			// gap: 16rpx;
 
			.topBox {
				display: flex;
				justify-content: space-between;
				width: 90%;
			}
			.tool {
				font-size: 28rpx;
				border-radius: 8rpx;
				padding: 12rpx 24rpx;
				background: #FFFFFF;
				box-shadow: 0 0 6rpx rgba(0, 0, 0, .15);
			}
		}
 
		.upopupAddress {
			height: 50vh;
			padding: 40rpx 20rpx;
 
			.singlePio {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
 
				.poiItem {
 
					.title {
						margin: 10rpx 0;
					}
 
					.contents {
						display: flex;
						justify-content: left;
						align-items: center;
						font-size: 25rpx;
						color: #c6c6c6;
 
						.distance {
							// padding-right: 10rpx;
							margin-right: 10rpx;
							border-right: solid;
							border-right-width: 1rpx;
							border-right-color: #c6c6c6;
							width: 100rpx;
						}
 
						.address {
							width: 500rpx;
						}
					}
				}
 
				.choice {}
			}
		}
	}
</style>